<script lang="ts">
/**
 * @author leo
 * @description #19530 其他栏目视图
 */

import { Component, Vue, Prop, Mixins } from "vue-property-decorator";
import { EventBus, ContentModal } from "feok-lib";
import TableWithSumMix from "../../mixins/TableWithSumMix";

import ImagesAdminLayout from "@/layouts/ImagesAdminLayout.vue";
import OtherTable from "@/components/OtherTable";
import TotalCard from "@/components/TotalCard";
import TitleCard from "@/components/TitleCard";
import GroupSelect from "@/components/GroupSelect";
import UploadOtherForm from "@/views/archives/other/UploadOtherForm.view.vue";

import {
  getApiAssetsFile,
  putApiAssetsFile,
  getApiAssetsGroup,
  postApiAssetsGroup,
  putApiAssetsFileId,
  deleteApiAssetsFileId,
  putApiAssetsGroupId,
  deleteApiAssetsGroupId,
  getApiAssetsFileSummary,
  postApiAssetsUseStatistics
} from "@/model";

@Component({
  components: {
    ContentModal,
    ImagesAdminLayout,
    OtherTable,
    TotalCard,
    TitleCard,
    UploadOtherForm,
    GroupSelect
  }
})
export default class ArchivesVideo extends Mixins(TableWithSumMix) {
  public query = {
    name: "",
    type: "FILE"
  };

  // 当期活动的分组
  public activedGroup = {
    name: "",
    id: 1
  };

  // 统计对象
  public totalObj = {
    num: 0,
    flow: 0,
    storage: 0
  };

  public videoUrl = "";
  public poster = "";
  public row: any = {};
  public loading = false;
  public data = [];
  public modalValue: boolean = false;
  public modalTitle: any = {
    upload: "上传文件",
    edit: "编辑文件"
  };
  public modalType: string = "";
  public dialogTableVisible = false;
  public videoObj = {};

  public menuArr = []; // 菜单数组
  public limit = 20;

  public addGroupVisible = false; // 添加分组开关
  public addGroupName = ""; // 添加分组名称
  public selectionArr = []; // 选中文件对象集合

  public pictureViewVistable = false;
  public changeFilesGroupVisible = false;
  public newFilesGroup: any = 0;

  public fetchDataAction = this.getApiAssetsFile;

  // 拉取资料列表
  public async getApiAssetsFile(query: any, page: number, limit: number) {
    try {
      const { data = [], total = 0 } = await getApiAssetsFile({
        ...query,
        groupId: this.activedGroup.id,
        pageNo: page,
        pageSize: limit
      });

      return {
        datas: data,
        total
      };
    } catch (err) {
      console.log(err);
    }
  }

  // 切换分类
  // item:分类对象
  public clickMenu(item: any) {
    try {
      this.activedGroup = JSON.parse(JSON.stringify(item));
      this.fetchData();
    } catch (e) {
      console.log(e);
    }
  }

  // 确定添加分组
  public async srueAddGroup() {
    try {
      await postApiAssetsGroup({
        name: this.addGroupName,
        type: "FILE" // 分类
      });
      EventBus.$emit("success", "操作成功");
      await this.fetchGroupList();
      this.addGroupName = "";
    } catch (error) {
      console.log(error);
    }
    this.addGroupVisible = false;
  }

  // 取消添加分组
  public closeAddGroupVisible() {
    this.addGroupName = "";
    this.addGroupVisible = false;
  }

  // 分组重命名
  public async onChangeGroupName(name: string) {
    try {
      await putApiAssetsGroupId({
        id: this.activedGroup.id,
        name,
        type: "FILE"
      });
      EventBus.$emit("success", "操作成功");

      await this.fetchGroupList();
      this.activedGroup.name = name;
    } catch (error) {
      console.log(error);
    }
  }

  //  删除分组
  public async onClickDelGroup() {
    const done = await this.$del(
      `仅删除分组，不删除文件，组内文件将自动归入未分组`
    );
    try {
      await deleteApiAssetsGroupId({ id: this.activedGroup.id });

      EventBus.$emit("success", "操作成功");
      this.refresh();
    } catch (error) {
    } finally {
      done();
    }
  }

  // 批量操作文件
  public async doFiles(params: any) {
    try {
      await putApiAssetsFile(params);
      EventBus.$emit("success", "操作成功");

      this.handleSearchData();
      this.clearSelected();
    } catch (error) {
      console.log(error);
    }
  }

  // 展开批量修改文件分组弹窗
  public openChangeFilesVistable() {
    this.newFilesGroup = this.activedGroup.id;
  }

  // 批量修改文件分组
  public async changeFiles() {
    this.doFiles({
      ids: this.selectionArr.map((res: any) => res.id),
      groupId: this.newFilesGroup
    });
    this.changeFilesGroupVisible = false;
  }

  // 批量删除文件
  public async delFiles() {
    this.doFiles({
      ids: this.selectionArr.map((res: any) => res.id),
      deleted: "1"
    });
  }

  // table 选中时
  // arr: 选中文件对象结合
  public handleSelect(arr: any) {
    this.selectionArr = arr;
  }

  // 计算点击数
  public async postApiAssetsUseStatistics(fileId: number) {
    try {
      await postApiAssetsUseStatistics({
        fileId,
        type: "DOWNLOAD" // DOWNLOAD/PLAY
      });
      this.getApiAssetsFileSummary();
    } catch (error) {
      console.log(error);
    }
  }

  // table 点击文件
  // item: 文件地址
  public onClickFile(item: any) {
    this.postApiAssetsUseStatistics(item.id);
  }

  /**
   *  操作 - 编辑
   *  id: 文件id
   */
  public handleEdit(row: any) {
    this.row = row;
    this.openModal("edit");
  }

  // 操作单个文件
  public async doFileById(params: any) {
    try {
      await putApiAssetsFileId(params);
      EventBus.$emit("success", "操作成功");
    } catch (error) {
      console.log(error);
    }
  }

  /**
   *  操作 - 删除
   *  row: 文件对象
   */
  public async handleDelete(row: any) {
    const done = await this.$del(row.name);
    try {
      this.doFileById({ id: row.id, deleted: "1" });
      this.handleSearchData();
    } catch (error) {
    } finally {
      done();
    }
  }

  // 操作 - 下载
  public async handleDownload(item: any) {
    this.postApiAssetsUseStatistics(item.id);

    const aElement = document.createElement("a");
    aElement.target = "_blank";
    aElement.href = item.url;
    document.body.appendChild(aElement);
    aElement.click();
    document.body.removeChild(aElement);
  }

  public openModal(type: string) {
    this.modalType = type;
    this.modalValue = true;
  }

  public onModalCancel() {
    this.row = {};
    this.modalValue = false;
  }

  public onModalDone() {
    this.onModalCancel();
    this.handleSearchData();
  }

  public clearSelected() {
    const ref = this.$refs.OtherTable as any;
    ref.doAction("clearSelection");
    this.selectionArr = [];
  }

  public async handleSearchData() {
    await this.fetchGroupList();
    if (this.menuArr.length) {
      await this.fetchData();
    }
  }

  // 拉取分组列表
  public async fetchGroupList() {
    try {
      this.menuArr = await getApiAssetsGroup({
        type: "FILE"
      });
    } catch (e) {
      console.log(e);
    }
  }
  public async refresh() {
    await this.fetchGroupList();
    if (this.menuArr.length) {
      this.activedGroup = this.menuArr[0];
      await this.fetchData();
      this.getApiAssetsFileSummary();
    }
  }

  // 拉去统计
  public async getApiAssetsFileSummary() {
    const result = await getApiAssetsFileSummary({ type: "FILE" });
    this.totalObj = result;
  }

  public mounted() {
    this.refresh();
  }
}
</script>

<template>
  <div class="video_admin_view">
    <!-- 统计模块 -->
    <TotalCard
      :num="totalObj.count"
      :flow="totalObj.handleSize"
      :storage="(totalObj.useSize/1024/1024/1024).toFixed(4)"
    ></TotalCard>

    <!-- 标题场景 -->
    <div slot="breadcrumb" class="video_admin_view-upload_wrap">
      <el-form
        ref="form"
        :model="query"
        :inline="true"
        size="mini"
        class="patch-el-form-search-wrap"
        @submit.native.prevent
        label-width="0px"
      >
        <el-form-item>
          <el-input
            v-model="query.name"
            clearable
            @keyup.enter.native="handleSearch"
            placeholder="文件名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="openModal('upload')">点击上传</el-button>
          <el-popover
            placement="bottom"
            width="325"
            trigger="click"
            v-model="changeFilesGroupVisible"
            @show="openChangeFilesVistable"
          >
            <template v-if="changeFilesGroupVisible">
              <p>选择分组</p>
              <GroupSelect v-model="newFilesGroup" :query="{type: 'FILE'}" style="margin:6px 0;"></GroupSelect>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="changeFilesGroupVisible = false">取消</el-button>
                <el-button type="primary" size="mini" @click="changeFiles">确定</el-button>
              </div>
            </template>
            <el-button
              slot="reference"
              style="margin-left:10px;"
              v-show="selectionArr && selectionArr.length>0"
            >修改分组</el-button>
          </el-popover>
          <el-button
            style="margin-left:10px;"
            v-show="selectionArr && selectionArr.length>0"
            @click="delFiles"
          >删除</el-button>
        </el-form-item>
      </el-form>
    </div>

    <ImagesAdminLayout>
      <!-- 左侧菜单 -->
      <div slot="menu" class="video_admin_view-menu_wrap">
        <ul class="video_admin_view-menu">
          <li
            v-for="(item,index) in menuArr"
            :key="index"
            class="video_admin_view-menu_li"
            :class="{'video_admin_view-menu_li-actived':activedGroup.id === item.id}"
            @click="clickMenu(item)"
          >
            <span class="feok-fr">{{item.acount}}</span>
            {{item.name}}
          </li>
        </ul>
        <el-popover placement="right" width="325" trigger="click" v-model="addGroupVisible">
          <p>添加分组</p>
          <el-input v-model="addGroupName" placeholder="请输入内容" style="margin:8px 0;"></el-input>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="closeAddGroupVisible">取消</el-button>
            <el-button type="primary" size="mini" @click="srueAddGroup">确定</el-button>
          </div>
          <el-button slot="reference" size="mini" plain class="video_admin_view-menu_new">
            <i class="iconfont icon-jia"></i> 新建分组
          </el-button>
        </el-popover>
      </div>

      <!-- 右侧内容 -->
      <div slot="content" class="video_admin_view-content_wrap">
        <!-- 分类操作 -->
        <TitleCard
          :name="activedGroup.name"
          :group-id="activedGroup.id"
          @on-change-group-name="onChangeGroupName"
          @on-click-del-group="onClickDelGroup"
        ></TitleCard>

        <!-- table -->
        <OtherTable
          ref="OtherTable"
          refName="OtherTableDo"
          slot="body"
          :data="data"
          :loading="loading"
          @on-download-file="onClickFile"
          @on-select="handleSelect"
          @on-select-all="handleSelect"
        >
          <template slot="firstColumn">
            <el-table-column
              reserve-selection
              type="selection"
              align="center"
              :resizable="false"
              width="45"
            ></el-table-column>
          </template>
          <template slot="handle">
            <el-table-column label="操作" fixed="right" align="right" width="100">
              <template slot-scope="{row}">
                <a @click="handleDownload(row)" title="下载">
                  <i class="iconfont icon-xiazai table-opt"></i>
                </a>
                <a @click="handleEdit(row)" title="编辑">
                  <i class="iconfont icon-bianji table-opt"></i>
                </a>
                <a @click="handleDelete(row)" title="删除">
                  <i class="iconfont icon-shanchu table-opt"></i>
                </a>
              </template>
            </el-table-column>
          </template>
        </OtherTable>
        <div style="margin-top:18px;">
          <el-pagination
            class="feok-fr"
            background
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page.sync="page"
            :page-size="limit"
            layout="prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </div>
    </ImagesAdminLayout>

    <!--模态框详情页 start-->
    <ContentModal v-model="modalValue" :title="modalTitle[modalType]" @on-cancel="onModalCancel">
      <UploadOtherForm
        v-if="modalType !== 'FILE'"
        :video-id="row.id"
        :obj="row"
        @on-cancel="onModalCancel"
        @on-done="onModalDone"
      ></UploadOtherForm>
    </ContentModal>
    <!--模态框详情页 end-->
  </div>
</template>

<style lang="less">
.video_admin_view {
  background: #fff;
  padding: 10px;
  min-height: 100%;
  display: flex;
  flex-direction: column;
}
.video_admin_view-upload_wrap {
  overflow: hidden;
  margin-bottom: 10px;
  .icon-daochu {
    vertical-align: text-bottom;
  }
}
.video_admin_view-menu_wrap {
  width: 90%;
  margin: 0 auto;
}
.video_admin_view-search {
  width: 100%;
  margin: 10px 0;
}
.video_admin_view-lately {
  color: #7b898f;
  line-height: 32px;
  font-size: 14px;
  cursor: pointer;
  padding: 0 8px;
  margin-bottom: 10px;
  i {
    margin-right: 8px;
  }
  &:hover {
    background: #fff;
    border-radius: 4px;
  }
}
.video_admin_view-menu {
  padding: 6px 0;
}
.video_admin_view-menu_li {
  color: #7b898f;
  position: relative;
  list-style-type: none;
  line-height: 24px;
  font-size: 14px;
  padding: 0 8px;
  margin: 8px 0;
  cursor: pointer;
  &:hover {
    .video_admin_view-menu_li-actived;
  }
}
.video_admin_view-menu_li-actived {
  &::before {
    content: "";
    position: absolute;
    left: -5%;
    top: 0;
    width: 4px;
    height: 24px;
    background: #409eff;
  }
  color: #2d8cf0;
  font-weight: bold;
}
.video_admin_view-menu_new {
  display: block;
  margin: 10px auto;
  .icon-jia {
    vertical-align: text-bottom;
  }
}

.video_admin_view-content_wrap {
  display: flex;
  flex: 1;
  flex-direction: column;
  padding: 0 0 10px 10px;
}
.video_admin_view-content_border {
  flex: 1;
  margin-top: 18px;
  overflow-x: hidden;
}
.video_admin_view-img {
  background: blue;
  width: 150px;
  height: 200px;
  float: left;
  margin: 10px 10px 0px 0;
}
</style>